package com.jusz.ddns.server.controller;

import com.jusz.ddns.server.config.DDNSProperty;
import com.jusz.ddns.server.config.NginxConfigFile;
import com.jusz.ddns.server.utils.FileTool;
import com.jusz.ddns.server.utils.JuszAssert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;

/**
 * @author: tcm
 * @date: 2021/8/25
 * @description IP上报
 */
@RestController
@RequestMapping("ipReport")
public class IPReportController {

    @Autowired
    DDNSProperty ddnsProperty;
    String ipCache = null;
    @Autowired
    HttpServletRequest request;
    private static final Logger LOG = LoggerFactory.getLogger(IPReportController.class);

    @PutMapping
    public void put(@RequestParam("secret") String secret) throws Exception {

        JuszAssert.hasText(secret, "secret must provide.");
        JuszAssert.hasText(ddnsProperty.getSecret(), "ddns secret not setting.");
        JuszAssert.isTrue(ddnsProperty.getSecret().equals(secret), "secret error.");

        String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }
        JuszAssert.hasText(ipAddress, "x-forwarded-for not found.");

        if (ipAddress.equals(ipCache)) {
            return;
        }

        LOG.info("Remote address: " + ipAddress);

        String nginxReloadScript = ddnsProperty.getNginx().getReloadScript();
        JuszAssert.hasText(nginxReloadScript, "Nginx reload script not setting.");

        for (NginxConfigFile configFile : ddnsProperty.getNginx().getConfigFiles()) {
            String connect = FileTool.readFileToString(configFile.getSource());
            connect = connect.replace("${IP_ADDRESS}", ipAddress);
            FileTool.stingToFile(configFile.getTarget(), connect);
        }

        // nginx config reload
        boolean isSuccess = execScript(nginxReloadScript);
        JuszAssert.isTrue(isSuccess, "Nginx config reload error.");

        ipCache = ipAddress;
    }

    private boolean execScript(String script) throws Exception {
        Process pro = Runtime.getRuntime().exec(script);
        int rel = pro.waitFor();
        if (rel != 0) {
            return false;
        }
        InputStream in = pro.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in));
        String result = read.readLine();
        LOG.info("Shell info:" + result);
        return true;
    }
}
